//
//  OPHelperAccountWriteViewController.m
//  OnePiece
//
//  Created by lanou on 15/10/31.
//  Copyright © 2015年 wsy. All rights reserved.
//

#import "OPHelperAccountWriteViewController.h"
#import "OPHelperAccountDetailCell.h"
#import "OPHelperAccountDataCell.h"
#import "OPDataPickerViewController.h"
#import "OPHelperAccountImageCell.h"
#import "OPHelperAccountTypeViewController.h"
#import "FMDatabase.h"

@interface OPHelperAccountWriteViewController () <UIScrollViewDelegate,UITableViewDataSource, UITableViewDelegate,UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UIButton *saveBtn;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *borderView;
@property (nonatomic, strong) UIPageControl *page;
@property (nonatomic, strong) NSArray *iconArray;
@property (nonatomic, strong) NSArray *nameArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *tableNameArray;
@property (nonatomic, strong) UIButton *btn;
@property (nonatomic, strong) FMDatabase *dataBase;
@property (nonatomic, assign) int i;
@end

@implementation OPHelperAccountWriteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    
    _backBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [_backBtn addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];
    _backBtn.frame = CGRectMake(20, 40, 30, 30);
    [_backBtn setImage:[UIImage imageNamed:@"zyciconfont-x (1)"] forState:(UIControlStateNormal)];
    [self.view addSubview:_backBtn];
    
    _saveBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [_saveBtn addTarget:self action:@selector(save) forControlEvents:(UIControlEventTouchUpInside)];
    _saveBtn.frame = CGRectMake(SCREEN_WIDTH - 50, 40, 30, 30);
    [_saveBtn setImage:[UIImage imageNamed:@"zyciconfont-bf-icon-correct"] forState:(UIControlStateNormal)];
    [self.view addSubview:_saveBtn];
    
    self.iconArray = @[@"zychelper_gouwu", @"zychelper_jiaotong", @"zychelper_jiudian", @"zychelper_yule", @"zychelper_meirong", @"zychelper_meishi", @"zychelper_kanbing", @"zychelper_riyong", @"zychelper_tingche", @"zychelper_qita"];
    self.nameArray = @[@"购物", @"交通", @"酒店", @"娱乐", @"美容", @"美食", @"看病", @"日用", @"停车", @"其他"];
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 80, SCREEN_WIDTH, 100)];
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 2, 100);
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
    _scrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
    
    UILabel *l = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH * 2, 1)];
    l.backgroundColor = [UIColor colorWithWhite:0.749 alpha:1.000];
    [_scrollView addSubview:l];
    
    for (int i = 0; i < 5; i++) {
        UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [btn setImage:[UIImage imageNamed:self.iconArray[i]] forState:(UIControlStateNormal)];
        btn.frame = CGRectMake(25 + SCREEN_WIDTH / 5.2 * i, 10, 40, 40);
        [btn addTarget:self action:@selector(didClickScrollBtn:) forControlEvents:(UIControlEventTouchUpInside)];
        [_scrollView addSubview:btn];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(25 + SCREEN_WIDTH / 5.2 * i, 60, 40, 20)];
        label.text = self.nameArray[i];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:13];
        [_scrollView addSubview:label];
        
        UIButton *btn1 = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [btn1 setImage:[UIImage imageNamed:self.iconArray[i + 5]] forState:(UIControlStateNormal)];
        btn1.frame = CGRectMake(SCREEN_WIDTH + 25 + SCREEN_WIDTH / 5.2 * i, 10, 40, 40);
        [btn1 addTarget:self action:@selector(didClickScrollBtn:) forControlEvents:(UIControlEventTouchUpInside)];
        [_scrollView addSubview:btn1];
        
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH + 25 + SCREEN_WIDTH / 5.2 * i, 60, 40, 20)];
        lab.textAlignment = NSTextAlignmentCenter;
        lab.text = self.nameArray[i + 5];
        lab.font = [UIFont systemFontOfSize:13];
        [_scrollView addSubview:lab];
    }
    
    _page = [[UIPageControl alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 20, 165, 40, 10)];
    _page.numberOfPages = 2;
    _page.currentPageIndicatorTintColor = [UIColor colorWithWhite:0.274 alpha:1.000];
    _page.pageIndicatorTintColor = [UIColor colorWithWhite:0.671 alpha:1.000];
    [self.view addSubview:_page];
    
    _borderView = [[UIView alloc]init];
    _borderView.layer.borderWidth = 1;
    _borderView.frame = CGRectMake(20 + SCREEN_WIDTH / 5.2, 5, 50, 80);
    _borderView.backgroundColor = [UIColor clearColor];
    _borderView.layer.borderColor = [[UIColor colorWithRed:0.886 green:0.369 blue:0.208 alpha:0.509] CGColor];
    [_scrollView addSubview:_borderView];
    
    NSArray *array1 = @[@"金额", @"类型"];
    NSArray *array2 = @[@"日期", @"备注", @"图片"];
    self.tableNameArray = @[array1, array2];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 180, SCREEN_WIDTH, SCREEN_HEIGHT - 180) style:(UITableViewStyleGrouped)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor colorWithWhite:0.941 alpha:1.000];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [_tableView registerClass:[OPHelperAccountDetailCell class] forCellReuseIdentifier:@"money"];
    [_tableView registerClass:[OPHelperAccountImageCell class] forCellReuseIdentifier:@"img"];
    [_tableView registerClass:[OPHelperAccountDataCell class] forCellReuseIdentifier:@"data"];
    [self.view addSubview:_tableView];
    
    _btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _btn.frame = CGRectMake(10, 325, SCREEN_WIDTH - 20, 40);
    _btn.backgroundColor = [UIColor colorWithRed:0.886 green:0.369 blue:0.208 alpha:1.000];
    [_btn setTitle:@"保存再记一笔" forState:(UIControlStateNormal)];
    [_btn addTarget:self action:@selector(saveAndAgain) forControlEvents:(UIControlEventTouchUpInside)];
    [_btn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [_tableView addSubview:_btn];
    

    
    
}

- (void)didClickScrollBtn:(UIButton *)btn
{
    self.i = btn.frame.origin.x / (SCREEN_WIDTH / 5.2);
    NSLog(@"%d",_i);
    [UIView animateWithDuration:0.5 animations:^{
        if (_i <= 4) {
            _borderView.frame = CGRectMake(20 + _i * SCREEN_WIDTH / 5.2, 5, 50, 80);
        }
        else
        {
            _borderView.frame = CGRectMake(SCREEN_WIDTH + 20 + (_i - 5) * SCREEN_WIDTH / 5.2, 5, 50, 80);
        }
    }];
    
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _page.currentPage = scrollView.contentOffset.x / SCREEN_WIDTH;
}


- (void)back
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)save
{
    OPHelperAccountDetailCell *cell1 = (OPHelperAccountDetailCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
    OPHelperAccountDetailCell *cell2 = (OPHelperAccountDetailCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:1]];
    if (cell1.textField.text.length == 0 || self.data.length == 0) {
        NSLog(@"信息输入不完整，请继续输入");
    }
    else
    {
        NSString *str = [self.data substringToIndex:11];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
        dic[@"money"] = cell1.textField.text;
        dic[@"moneyTypeCh"] = self.moneyTypeCh;
        dic[@"moneyTypeEng"] = self.moneyTypeEng;
        dic[@"data"] = str;
        dic[@"remark"] = cell2.textField.text;
        dic[@"typeImg"] = self.iconArray[_i];
        dic[@"typeCh"] = self.nameArray[_i];
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        if ([user arrayForKey:str]) {
            NSMutableArray *arr = [NSMutableArray arrayWithArray:[user arrayForKey:str]];
            [arr addObject:dic];
            [user setObject:arr forKey:str];
        }
        else
        {
            NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
            [arr addObject:dic];
            [user setObject:arr forKey:str];
        }

        [self dismissViewControllerAnimated:YES completion:^{
            self.freshBlock(str);
        }];
    }
}

- (void)saveAndAgain
{
    OPHelperAccountDetailCell *cell1 = (OPHelperAccountDetailCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
    OPHelperAccountDetailCell *cell2 = (OPHelperAccountDetailCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:1]];
    OPHelperAccountDataCell *cell3 = (OPHelperAccountDataCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    OPHelperAccountDataCell *cell4 = (OPHelperAccountDataCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    
    if (cell1.textField.text.length == 0 || self.data.length == 0) {
        NSLog(@"信息输入不完整，请继续输入");
    }
    else
    {
        NSString *str = [self.data substringToIndex:11];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
        dic[@"money"] = cell1.textField.text;
        dic[@"moneyTypeCh"] = self.moneyTypeCh;
        dic[@"moneyTypeEng"] = self.moneyTypeEng;
        dic[@"data"] = str;
        dic[@"remark"] = cell2.textField.text;
        dic[@"typeImg"] = self.iconArray[_i];
        dic[@"typeCh"] = self.nameArray[_i];
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setObject:dic forKey:str];
        [self dismissViewControllerAnimated:YES completion:^{
            self.freshBlock(str);
        }];
    cell1.textField.text = @"";
    cell2.textField.text = @"";
    cell3.dataLabel.text = @"";
    cell4.dataLabel.text = @"";
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
                case 0:
                {
                    OPHelperAccountDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"money" forIndexPath:indexPath];
                    cell.textField.keyboardType = UIKeyboardTypeNumberPad;
                    cell.textField.delegate = self;
                    cell.content.text = @"金额";
                    return cell;
                }
                    break;
                case 1:
                {
                    OPHelperAccountDataCell *cell = [tableView dequeueReusableCellWithIdentifier:@"data" forIndexPath:indexPath];
                    cell.content.text = @"类型";
                    
                    return cell;
                }
                    break;
                default:
                    return nil;
                    break;
            }
            break;
        case 1:
            switch (indexPath.row) {
                case 0:
                {
                    OPHelperAccountDataCell *cell = [tableView dequeueReusableCellWithIdentifier:@"data" forIndexPath:indexPath];
                    cell.content.text = @"日期";
                    return cell;
                }
                    break;
                case 1:
                {
                    OPHelperAccountDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"money" forIndexPath:indexPath];
                    cell.content.text = @"备注";
                    cell.textField.delegate = self;

                    return cell;
                }
                    break;
                case 2:
                {
                    OPHelperAccountImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"img" forIndexPath:indexPath];
                    cell.content.text = @"照片";
                    return cell;
                }
                    break;
                default:
                    return nil;
                    break;
            }
            break;
        default:
            return nil;
            break;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row){
                case 0:

                    break;
                case 1:
                {
                    OPHelperAccountTypeViewController *typeVC = [[OPHelperAccountTypeViewController alloc]init];
                    typeVC.typeBlock = ^(NSString *typeCh, NSString *typeEng)
                    {
                        OPHelperAccountDataCell *cell = (OPHelperAccountDataCell *)[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
                        cell.dataLabel.text = typeCh;
                        self.moneyTypeCh = typeCh;
                        self.moneyTypeEng = typeEng;
                    };
                    [self presentViewController:typeVC animated:YES completion:nil];
                    
                    
                }
                    break;
                default:
                    break;
            }
            break;
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                {
                    OPDataPickerViewController *pickVC = [[OPDataPickerViewController alloc]init];
                    pickVC.dataBlock = ^(NSString *string)
                    {
                        NSString *str = [string substringWithRange:NSMakeRange(0, string.length - 3)];
                        OPHelperAccountDataCell *cell = (OPHelperAccountDataCell *)[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
                        cell.content.text = @"日期";
                        cell.dataLabel.text = str;
                        self.data = str;
                    };
                    [self presentViewController:pickVC animated:YES completion:nil];
                }
                    break;
                case 1:
                    
                    break;
                case 2:
                {
                    
                    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                        picker.delegate = self;//设置UIImagePickerController的代理，同时要遵循UIImagePickerControllerDelegate，UINavigationControllerDelegate协议
                        picker.allowsEditing = YES;//设置拍照之后图片是否可编辑，如果设置成可编辑的话会在代理方法返回的字典里面多一些键值。PS：如果在调用相机的时候允许照片可编辑，那么用户能编辑的照片的位置并不包括边角。
                        picker.sourceType = UIImagePickerControllerSourceTypeCamera;//UIImagePicker选择器的类型，UIImagePickerControllerSourceTypeCamera调用系统相机
                        [self presentViewController:picker animated:YES completion:nil];

                    }
                }
                    break;
                    
                default:
                    break;
            }

        
            break;
        default:
            break;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 2;
            break;
        case 1:
            return 3;
            break;
        default:
            return 0;
            break;
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = info[@"UIImagePickerControllerEditedImage"];
    OPHelperAccountImageCell *cell = (OPHelperAccountImageCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    cell.imgView.image = image;

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
